package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.UriUtils;
import com.king.zxing.util.CodeUtils;
import com.stark.file.transfer.core.FileInfo;
import com.stark.file.transfer.core.TfConst;
import com.stark.file.transfer.core.TfContactInfo;
import com.stark.file.transfer.core.Transferable;
import com.stark.file.transfer.core.TransferableSendManager;
import com.stark.file.transfer.core.TransferableType;

import java.io.IOException;
import java.net.ServerSocket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.SelectFileBean;
import flc.ast.databinding.ActivityFileSendShowQrBinding;
import flc.ast.utils.AppSpUtils;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.bean.ContactInfo;
import stark.common.basic.constant.FileType;
import stark.common.basic.utils.BroadcastReceiverUtil;
import stark.common.basic.utils.IOUtil;
import stark.common.basic.utils.RxUtil;

public class FileSendShowQrActivity extends BaseAc<ActivityFileSendShowQrBinding> implements TransferableSendManager.ISendListener {

    public static List<SelectFileBean> listSend;
    //是否跳转到发送文件界面的标志
    private boolean hasGoFileSend = false;
    private BroadcastReceiver mNetReceiver;
    private ImageView mQrCodeView;
    private int picNum, videoNum, contactsNum;
    private long picSize, videoSize, contactsSize;
    private List<SelectFileBean> listSave = new ArrayList<>();

    @Override
    protected int onCreate() {
        return R.layout.activity_file_send_show_qr;
    }

    @Override
    protected void initView() {
        mDataBinding.ivFileSendBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.tvConfirm.setOnClickListener(this);
        mDataBinding.tvFileSize.setText(ConvertUtils.byte2FitMemorySize(TransferableSendManager.getInstance().getTransferableTotalSize(), 0));
        long size = TransferableSendManager.getInstance().getTransferableTotalSize();
        long mins = (long) (size / (28.8 * 1024 * 800));
        if (mins == 0) {
            mDataBinding.tvFileSize.setText(getString(R.string.file_size, ConvertUtils.byte2FitMemorySize(size, 2), 1));
        } else {
            mDataBinding.tvFileSize.setText(getString(R.string.file_size, ConvertUtils.byte2FitMemorySize(size, 2), mins));
        }
        hasGoFileSend = false;
        ImageView imageView = mDataBinding.ivQrCode;
        mQrCodeView = imageView;

        updateQrView(imageView);
        //注册监听网络状态的广播接收器
        registerNetReceiver();

        //开启服务端，等待客户端扫码并连接
        TransferableSendManager.getInstance().createServerSocket(new TransferableSendManager.IServerCallback() {
            @Override
            public void onFirstClientCome() {
                //客户端扫码并连接了，则跳转到发送界面开始发送文件
//                startActivity(FileSendActivity.class);
                showSendProgress();
//                hasGoFileSend = true;
//                onBackPressed();
            }
        });

        //创建等待客户端连接的任务
        createCheckConnectTask();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.tvConfirm://完成
                onBackPressed();
                ActivityUtils.finishActivity(SelFileActivity.class);
                break;
        }
    }

    @Override
    protected void initData() {
        for (SelectFileBean bean : listSend) {
            if (bean.getType() == 1) {
                picNum++;
                picSize += bean.getSize();
            } else if (bean.getType() == 2) {
                videoNum++;
                videoSize += bean.getSize();
            } else if (bean.getType() == 3) {
                contactsNum++;
                contactsSize += bean.getSize();
            }
        }
        mDataBinding.tvPicSize.setText(getString(R.string.pic_size, picNum, ConvertUtils.byte2FitMemorySize(picSize, 0)));
        mDataBinding.tvVideoSize.setText(getString(R.string.video_size, videoNum, ConvertUtils.byte2FitMemorySize(videoSize, 0)));
        mDataBinding.tvContactsSize.setText(getString(R.string.contacts_size, contactsNum, ConvertUtils.byte2FitMemorySize(contactsSize, 0)));
    }

    private void showSendProgress() {
        mDataBinding.llShowQr.setVisibility(View.GONE);
        mDataBinding.llTransfer.setVisibility(View.VISIBLE);
        mDataBinding.tvTitle.setText(R.string.transfer_ing);
        TransferableSendManager manager = TransferableSendManager.getInstance();
        manager.setSendListener(this);
        manager.setSendListener1(new TransferableSendManager.ISendListener1() {
            @Override
            public void onCompleteItem(Transferable transferable, boolean success) {
                if (success) {
                    SelectFileBean bean = new SelectFileBean();
                    TransferableType type = transferable.getTransferType();
                    if (type == TransferableType.FILE) {
                        FileInfo fileInfo = (FileInfo) transferable;
                        if (fileInfo.getFileType() == FileType.IMAGE) {
                            bean.setType(1);
                            bean.setPath(UriUtils.uri2File(Uri.parse(fileInfo.getUriStr())).getAbsolutePath());
                            listSave.add(bean);
                        } else if (fileInfo.getFileType() == FileType.VIDEO) {
                            bean.setType(2);
                            bean.setPath(UriUtils.uri2File(Uri.parse(fileInfo.getUriStr())).getAbsolutePath());
                            listSave.add(bean);
                        }
                    } else if (type == TransferableType.CONTACT) {
                        TfContactInfo tfContactInfo = (TfContactInfo) transferable;
                        Log.e("test", "onReceivedTransferable: " + tfContactInfo.getContactInfoList().size());
                        for (ContactInfo contactInfo : tfContactInfo.getContactInfoList()) {
                            SelectFileBean contactBean = new SelectFileBean();
                            contactBean.setType(3);
                            contactBean.setName(contactInfo.getName());
                            contactBean.setPath(contactInfo.getPhone());
                            listSave.add(contactBean);
                        }
                    }
                }
            }
        });
    }


    /**
     * 注册监听网络状态变化的广播接收器，以自动更新二维码
     */
    private void registerNetReceiver() {
        if (mNetReceiver == null) {
            mNetReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    updateQrView(mQrCodeView);
                }
            };
            IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
            BroadcastReceiverUtil.registerReceiver(mContext, mNetReceiver, filter);
        }
    }


    private ServerSocket mServerSocket;

    /**
     * 创建等待客户端连接的任务以检测客户端是否跟本设备在同一局域网内
     */
    private void createCheckConnectTask() {
        RxUtil.create(new RxUtil.Callback<Boolean>() {
            @Override
            public void doBackground(ObservableEmitter<Boolean> emitter) {
                try {
                    mServerSocket = new ServerSocket(TfConst.IP_PORT_CHECK_CONNECT);
                    mServerSocket.accept();
                    mServerSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                emitter.onNext(true);
            }

            @Override
            public void accept(Boolean obj) {
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (!hasGoFileSend) {
            TransferableSendManager.getInstance().clear();
        }
        unregisterNetReceiver();
        destroyCheckConnectTask();
    }


    /**
     * 注销监听网络状态变化的广播接收器
     */
    private void unregisterNetReceiver() {
        if (mNetReceiver != null) {
            unregisterReceiver(mNetReceiver);
            mNetReceiver = null;
        }
    }

    /**
     * 销毁检测任务
     */
    private void destroyCheckConnectTask() {
        IOUtil.close(mServerSocket);
    }

    private void updateQrView(ImageView imageView) {
        int height = SizeUtils.dp2px(300);
        String ip = getIp();
        if (TextUtils.isEmpty(ip)) {
            //无网络时，将无法获取到ip，则设置一个无效的二维码
            ip = TfConst.INVALID_IP;
        }
        Bitmap bitmap = CodeUtils.createQRCode(ip, height);
        imageView.setImageBitmap(bitmap);
    }


    /**
     * 返回当前设备的ip地址
     *
     * @return
     */
    private String getIp() {
        String ip = NetworkUtils.getIPAddress(true);
        ;
        try {
            String wifiIp = NetworkUtils.getIpAddressByWifi();
            //这里添加这样的处理是因为发现有在小米的Android12系统的手机上通过NetworkUtils.getIPAddress无法
            //获取到局域网地址，而是直接获取到公网地址
            if (!TextUtils.isEmpty(wifiIp) && wifiIp.startsWith("192")) {
                return wifiIp;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

    @Override
    public void onCompleteCount(int totalCount, int haveSendCount) {
        mDataBinding.sbProgress.setMax(totalCount);
        mDataBinding.sbProgress.setProgress(haveSendCount);
        double percent = (double) haveSendCount / totalCount;
        mDataBinding.tvProgress.setText((int) (percent * 100) + getString(R.string.unit_percent));
        if (totalCount == haveSendCount) {
            mDataBinding.tvProgress.setText(100 + getString(R.string.unit_percent));
            List<SelectFileBean> listSp = AppSpUtils.getTransferRecordList();
            if (listSp != null && listSp.size() > 0) {
                listSp.addAll(listSave);
                AppSpUtils.saveTransferRecordList(listSp);
            } else {
                AppSpUtils.saveTransferRecordList(listSave);
            }
            mDataBinding.tvConfirm.setVisibility(View.VISIBLE);
        }
    }
}